import { createApp, h, type App, ref, type Component } from 'vue'
import { Popup, type PopupProps } from 'vant'

let fragment: HTMLElement | null = null
let _tipModal: App<Element> | null = null
const open = ref(true)
/**
 *
 * @param childComp 子组件
 * @param childProps 子组件属性
 * @param modalProps 弹窗属性
 * @returns
 */
function showCustomModal(
  childComp: Component,
  childProps: any,
  modalProps?: PopupProps
): Promise<void> {
  return new Promise((resolve) => {
    fragment = document.createElement('div')
    fragment.id = 'modalFragment'
    document.body.appendChild(fragment)
    const dialog = () =>
      h(
        Popup,
        {
          ...modalProps,
          show: open.value,
          round: true,
          safeAreaInsetBottom: true,
          safeAreaInsetTop: true,
          style: {
            background: 'none',
            overflow: 'visible'
          },
          onClosed: () => {
            closeCustomModal()
          }
        },
        {
          default: () =>
            h(childComp, {
              onClose: () => {
                open.value = false
                resolve()
              },
              ...childProps
            })
        }
      )
    _tipModal = createApp(dialog)
    _tipModal.mount(fragment)
    window.addEventListener('unload', () => {
      closeCustomModal()
      resolve()
    })
  })
}
function closeCustomModal() {
  open.value = true
  _tipModal?.unmount()
  fragment?.remove()
  _tipModal = null
  fragment = null
}
export { showCustomModal, closeCustomModal }
